import React, { Component } from 'react';
import ThePagination from "@/components/ThePagination";
import { Form, Input, Select, Space, message, Button, Radio, DatePicker, Modal } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import { apiStockLibraryManageAdd, apiStockLibraryManagePage, apiGetAllWmsLibraryType, apiGetAllProprietaryStore, apiStockLibraryManageView, apiSysUserList, apiStockLibraryManageDel, apiStockLibraryManageEdit } from '@/request/storageManager/store.js'
import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend'
import store from "@/store/store"
const { Option } = Select
export default class OutPut extends Component {
    constructor() {
        super()
        this.formRef = React.createRef()
        this.queryFormRef = React.createRef()

        this.state = {
            isModalVisible: false,
            allWmsLibraryType: [],
            columns: [
                {
                    title: "仓库编码",
                    dataIndex: "id",
                    key: "id",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "商家名称",
                    dataIndex: "merchantName",
                    key: "merchantName",
                    render: (text, render) => {
                        return text
                    }
                },

                {
                    title: "商家类型",
                    dataIndex: "merchantType",
                    key: "merchantType",
                    render: (text, render) => {
                        if (text == 0) {
                            return '实体门店'
                        } else if (text == 1) {
                            return '酒店'
                        } else if (text == 2) {
                            return '医院'
                        } else if (text == 3) {
                            return '上门服务'
                        } else if (text == 4) {
                            return '线上店铺'
                        }
                    }
                },

                {
                    title: "仓库名称",
                    dataIndex: "name",
                    key: "name",
                    render: (text, render) => {
                        return text
                    }
                },
                {
                    title: "仓库负责人",
                    dataIndex: "managerName",
                    key: "managerName",
                    render: (text, render) => {
                        return text
                    }
                },

                {
                    title: "联系方式",
                    dataIndex: "managerPhone",
                    key: "managerPhone",
                    render: (text, render) => {
                        return text
                    }
                }, {
                    title: "仓库类型",
                    dataIndex: "type",
                    key: "type",
                    render: (text, render) => {
                        return text == 0 ? '大库仓' : '门店仓'
                    }
                }, {
                    title: "是否默认",
                    dataIndex: "isDefault",
                    key: "isDefault",
                    render: (text, render) => {
                        return text ? '否' : '是'
                    }
                }, {
                    title: "是否委外",
                    dataIndex: "isOutsource",
                    key: "isOutsource",
                    render: (text, render) => {
                        return text ? '否' : '是'
                    }
                }, {
                    title: "操作",
                    dataIndex: "serviceShowFile",
                    key: "serviceShowFile",
                    render: (text, render) => {
                        return <div>
                            {
                                render.isDefault && render.isOutsource ?
                                    <TheButton haspermi={['storage:store:storeEdit']} onClick={() => this.edit(render)}>编辑</TheButton>
                                    : null}
                        </div>
                    }
                },
            ],
            dataSource: [],
            pageData: {
                pageNo: 1,
                pageSize: 10

            },
            total: 0,
            storeId: '',
            storeName: "",
            modalTitle: '新增仓库',
            userList: [],
            newColumns: [],
            form_show: true,
            searchOption: [
                { field: 'libraryName', label: '仓库名称/编码', placeholder: '仓库名称/编码', required: false, rules: [], type: 'Input', defaultValue: '' },
                { field: 'storeName', label: '商家名称', placeholder: '商家名称', required: false, rules: [], type: 'Input', defaultValue: '' },
                // { field: 'managerPhone', label: '联系方式', placeholder: '联系方式', required: false, rules: [], type: 'InputNumber', defaultValue: '' },
            ],
            queryForm: {},
            storeList: [],
            isOutsource: 1
        }
    }
    componentDidMount() {
        this.onColumnsFilter(this.state.columns)
        this.getUserList()
        this.getData()
        this.getAllStore()
        this.getAllWmsLibraryType()
    }
    async getUserList() {
        let res = await apiSysUserList()
        if (res.code === 0) {
            this.setState({
                userList: res.data
            })
        }
    }
    getAllStore() {
        apiGetAllProprietaryStore().then(res => {
            if (res.code == 0) {
                this.setState({
                    storeList: res.data
                })
            }
        })
    }
    getAllWmsLibraryType() {
        apiGetAllWmsLibraryType().then(res => {
            if (res.code == 0) {
                this.setState({
                    allWmsLibraryType: Object.keys(res.data).map(key => {
                        return {
                            label: key,
                            value: res.data[key]
                        }
                    })
                })
            }
        })
    }
    getData(values) {
        let { pageNo, pageSize } = this.state.pageData
        this.setState({
            queryForm: values === undefined ? this.state.queryForm : { ...values }
        }, async () => {
            let res = await apiStockLibraryManagePage({
                pageNo: this.state.pageData.pageNo,
                pageSize: this.state.pageData.pageSize,
                ...this.state.queryForm
            })
            if (res.code === 0) {
                this.setState({
                    dataSource: res.data,
                    total: res.totalCount
                })
            }
        })

    }
    async del(row) {
        React.$confirm({
            title: "提示",
            type: 'warning',
            content: "确定是否删除？",
            onOk: async () => {
                let res = await apiStockLibraryManageDel({ id: row.id })
                if (res.code === 0) {
                    this.pageChange(1, 10)
                    React.$message({
                        type: 'success',
                        content: res.codeMessage
                    })
                } else {
                    React.$message({
                        type: 'warning',
                        content: res.codeMessage
                    })
                }
            }
        });
    }
    onAdd = () => {
        this.setState({
            isModalVisible: true, modalTitle: '新增', storeId: '',
            isOutsource: 1
        }, () => {
            this.formRef.current.resetFields()
        })
    }
    async edit(row) {
        let res = await apiStockLibraryManageView({ id: row.id })
        if (res.code === 0) {
            this.setState({
                isModalVisible: true,
                storeId: row.id,
                modalTitle: '编辑',
                isOutsource: row.isOutsource
            }, () => {
                this.formRef.current.setFieldsValue({
                    name: res.data.name, managerUserId: res.data.managerUserId,
                    dataId: row.dataId,
                    wmsLibraryType: row.wmsLibraryType,
                    isOutsource: row.isOutsource,
                })
            })

        }
    }
    async onFinish(values) {
        let { managerUserId, name, dataId, isOutsource, wmsLibraryType } = values
        let row = this.state.userList.filter(item => item.userId === managerUserId)[0]
        console.log(values, row);

        let { userName, userMobile } = row
        if (this.state.storeId === '') {
            let res = await apiStockLibraryManageAdd({
                dataId, name, managerUserId, managerName: userName, managerPhone: userMobile,
                isOutsource, wmsLibraryType: wmsLibraryType || ''
            })
            if (res.code === 0) {
                message.success(res.codeMessage)
                this.reset()
                this.setState({
                    isModalVisible: false,
                    storeId: ''
                }, () => this.pageChange(1, 10))
            }
        } else {
            let res = await apiStockLibraryManageEdit({
                id: this.state.storeId, managerUserId, name, managerName: userName, managerPhone: userMobile,
                isOutsource, wmsLibraryType: wmsLibraryType || ''
            })
            if (res.code === 0) {
                message.success(res.codeMessage)
                this.reset()
                this.setState({
                    isModalVisible: false,
                    storeId: ''
                }, () => this.pageChange(1, 10))
            }
        }
    }

    reset() {
        this.formRef.current.setFieldsValue({
            name: '', managerUserId: undefined, dataId: null
        })
        this.setState({
            isModalVisible: false,
        })
    }

    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo, pageSize
            }
        }, () => {
            this.getData()
        })
    };
    onCancel() {
        this.reset()
        this.setState({ isModalVisible: false })
    }
    onReset() {
        this.setState({
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }
    onColumnsFilter(value) {
        this.setState({
            newColumns: value
        })
    }
    onFormSearch(values) {
        this.setState({
            pageData: { pageNo: 1, pageSize: 10 }
        }, () => {
            this.getData(values)
        })
    }
    render() {
        let { isModalVisible, allWmsLibraryType, storeList, isOutsource, columns, userList, dataSource, modalTitle, pageData, storeId, total, form_show, searchOption, newColumns } = this.state
        return (
            <div className="p-layout-box commodity-examine">
                <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
                    onGetValues={(values) => this.onFormSearch(values)}
                    onReset={(values) => this.onReset(values)}
                >
                </TheQueryForm>
                <TheTableExtend
                    columns={columns}
                    onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
                    onTableRefresh={() => this.getData()}
                    onColumnsFilter={(value) => this.onColumnsFilter(value)}
                >
                    <TheButton haspermi={['storage:store:storeAdd']} size="middle" onClick={() => this.onAdd()} type="primary" >新增</TheButton>
                </TheTableExtend>
                <TheTable
                    scroll={{ x: "max-content", y: '63vh' }}
                    columns={newColumns}
                    dataSource={dataSource}
                />
                <ThePagination
                    pageNo={pageData.pageNo}
                    pageSize={pageData.pageSize}
                    total={total}
                    pageChange={this.pageChange}
                />
                <Modal title={modalTitle} visible={isModalVisible} width="40%"
                    onCancel={() => this.onCancel()} footer={null}
                >
                    <Form
                        labelCol={{
                            span: 6,
                        }}
                        wrapperCol={{
                            span: 18,
                        }}
                        ref={this.formRef}
                        onFinish={(values) => this.onFinish(values)}

                    >
                        <Form.Item
                            label="自营商家"
                            name="dataId"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择商家',
                                },
                            ]}
                        >
                            <Select placeholder='请选择商家' disabled={storeId}>
                                {
                                    storeList.length > 0 && storeList.map(item => {
                                        return <Option value={item.storeId}>{item.storeName}</Option>
                                    })
                                }

                            </Select>

                        </Form.Item>
                        <Form.Item
                            label="仓库名称"
                            name="name"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入仓库名称',
                                },
                            ]}
                        >
                            <Input style={{
                            }} placeholder='仓库名称' maxLength={20} />
                        </Form.Item>
                        <Form.Item
                            label="负责人姓名"
                            name="managerUserId"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择负责人',
                                },
                            ]}
                        >
                            <Select placeholder='请选择负责人' >
                                {
                                    userList.length > 0 && userList.map(item => {
                                        return <Option value={item.userId}>{item.userName}</Option>
                                    })
                                }

                            </Select>

                        </Form.Item>
                        <Form.Item
                            label="是否委外仓"
                            name="isOutsource"
                            rules={[
                                {
                                    required: true,
                                    message: '请选择是否委外',
                                },
                            ]}

                        >
                            <Radio.Group disabled={storeId && isOutsource === 0}>
                                <Radio value={0}>是</Radio>
                                <Radio value={1}>否</Radio>
                            </Radio.Group>
                        </Form.Item>
                        <Form.Item
                            noStyle
                            shouldUpdate={(prevValues, curValues) => prevValues.isOutsource !== curValues.isOutsource}
                        >
                            {
                                ({ getFieldValue }) => {
                                    return getFieldValue('isOutsource') == 0 ?
                                        <Form.Item
                                            label="WMS仓库类型"
                                            name="wmsLibraryType"
                                            rules={[
                                                {
                                                    required: true,
                                                    message: '请选择WMS仓库类型',
                                                },
                                            ]}
                                        >
                                            <Select placeholder='请选择WMS仓库类型' allowClear
                                                disabled={storeId && isOutsource === 0}
                                            >
                                                {
                                                    allWmsLibraryType.length > 0 && allWmsLibraryType.map(item => {
                                                        return <Option value={item.label}>{item.value}</Option>
                                                    })
                                                }

                                            </Select>
                                        </Form.Item> : null
                                }
                            }

                        </Form.Item>

                        <Form.Item wrapperCol={{
                            offset: 8,
                            span: 16,
                        }}>
                            <Space size="small" style={{ marginLeft: 10 }}>

                                <Button type="default" onClick={() => this.reset()}>
                                    取消
                                </Button>
                                <Button type="primary" htmlType="submit">
                                    确定
                                </Button>
                            </Space>
                        </Form.Item>
                    </Form>
                </Modal>
            </div >
        );
    }
}
